package com.zp.crm.Controller.UserController;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.google.gson.Gson;
import com.zp.crm.entity.User.UserEntity;
import com.zp.crm.service.UserService.UserService;
import com.zp.crm.util.targetLog.Log;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	public UserService userService;
	
	Gson gson=new Gson();
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@Log(name="登录")
	public void LoginUser(HttpServletRequest request,HttpServletResponse response,Model model){
		//跨域资源
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setContentType("text/html;charset=utf-8");
		String username = request.getParameter("un");
		String password = request.getParameter("pw");
		Map<String, Object> map=userService.LoginSelectByName(username,password);
		if((boolean) map.get("success")){
			String ip = request.getHeader("x-forwarded-for");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			String code=(String) map.get("LoginUid");
			userService.LoginIpAndTime(code,ip,new Date());
		}
		try {
			PrintWriter out = response.getWriter();
			String json=gson.toJson(map);
			out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value="/select",method=RequestMethod.POST)
	public void UserList(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");
		String pagestr=request.getParameter("page");
		int page=1,size=10;
		if(pagestr != null){
			page=Integer.parseInt(pagestr);
		}
		Map<String, Object> map=userService.SelectByList(page,size);
		try {
			PrintWriter out = response.getWriter();
			String a=(String) map.get("message");
			out.println(a);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	@RequestMapping(value="/stutsup",method=RequestMethod.POST)
	public void UserStutsUpdate(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");
		String code=request.getParameter("code");
		String stuts=request.getParameter("stuts");
		UserEntity entity=null;
		if(stuts!=null && stuts.equals("0")){
			entity=new UserEntity(code, null, Integer.parseInt(stuts));
		}
		if(stuts!=null && stuts.equals("1")){
			entity=new UserEntity(code, null, Integer.parseInt(stuts));
		}
		if(stuts!=null && stuts.equals("已删除")){
			entity=new UserEntity(code, stuts, 99);
		}
		if(stuts!=null && stuts.equals("正常")){
			entity=new UserEntity(code, stuts, 99);
		}	
		Map<String, Object> map=new HashMap<>();
		if(entity != null){
			map=userService.UserStutsUpdate(entity);
		}else{
			map.put("success", true);
			map.put("message", "请以正确形式进行操作");
		}
		try {
			PrintWriter out = response.getWriter();
			String json=gson.toJson(map);
			out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	@RequestMapping(value="/selectpage",method=RequestMethod.POST)
	public void SelectCraetePage(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");
		String username=request.getParameter("username");
		String name=request.getParameter("name");
		String stuts=request.getParameter("stuts");
		String pagestr=request.getParameter("page");
		int page=1,size=10;
		if(pagestr !=null){
			page=Integer.parseInt(pagestr);
		}
		Map<String, Object> map=userService.SelectCreatePage(username,name,stuts,page,size);
		try {
			PrintWriter out = response.getWriter();
			String a=(String) map.get("message");
			out.println(a);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value="/userRoidedit",method=RequestMethod.POST)
	public void UserRoidEdit(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");
		String code=request.getParameter("code");
		String obj=request.getParameter("obj");
		Map<String, Object> map=userService.UserRoidUpdate(code,obj);
		try {
			PrintWriter out = response.getWriter();
			String json=gson.toJson(map);
			out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value="/name",method=RequestMethod.POST)
	public void UserNameTrueNameSelect(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");
		String name=request.getParameter("name");
		String tname=request.getParameter("tname");
		Map<String, Object> map=userService.UserNameTrueNameSelect(name,tname);
		try {
			PrintWriter out = response.getWriter();
			String json=gson.toJson(map);
			out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public void Insert(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");
		String code=request.getParameter("code");
		String username=request.getParameter("username");
		String pwd=request.getParameter("pwd");
		String tname=request.getParameter("tname");	
		UserEntity entity=new UserEntity(code, username, pwd, tname,"1000", "正常", 0, new Date());
		Map<String, Object> map=userService.insert(entity);
		try {
			PrintWriter out = response.getWriter();
			String json=gson.toJson(map);
			out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value="/selectById",method=RequestMethod.POST)
	public void SelectByCode(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");
		String code=request.getParameter("code");
		Map<String, Object> map= new HashMap<>();
		if(code != null){
			map=userService.selectById(code);
		}else{
			map.put("success", false);
			map.put("message", "请正确操作！");
		}
		try {
			PrintWriter out = response.getWriter();
			String json=gson.toJson(map);
			out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@RequestMapping(value="/selectyzpwd",method=RequestMethod.POST)
	public void SelectUserNamePwd(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		Map<String, Object> map= userService.SelectUserNamePwd(name,pwd);
		try {
			PrintWriter out = response.getWriter();
			String json=gson.toJson(map);
			out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	@RequestMapping(value="/editPwd",method=RequestMethod.POST)
	public void EditPwd(HttpServletRequest request,HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");
		String code=request.getParameter("code");
		String pwd=request.getParameter("pwd");
		Map<String, Object> map= userService.EditUserPwd(code,pwd);
		try {
			PrintWriter out = response.getWriter();
			String json=gson.toJson(map);
			out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@RequestMapping(value="/editimg",method=RequestMethod.POST)
	public void UpdateLoadImg(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
		response.setContentType("text/html;charset=utf-8");
		String code=request.getParameter("code");
		String fileName="";
    	String attachmentName="";
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		if(multipartResolver.isMultipart(request)){  
            //转换成多部分request    
        	 MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            while(iter.hasNext()){  
            	fileName="";
            	attachmentName="";
                //取得上传文件  
                MultipartFile file = multiRequest.getFile(iter.next());  
                if(file != null){  
                    //取得当前上传文件的文件名称  
                    String myFileName = file.getOriginalFilename();  
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
                    if(myFileName.trim() !=""){  
                        System.out.println(myFileName);
                        myFileName=myFileName.split("\\.")[myFileName.split("\\.").length-1];
                        System.out.println(myFileName);
                        if(myFileName.equals("jpg")||myFileName.equals("png")||myFileName.equals("gif")){
                        	//重命名上传后的文件名  
                        	fileName = UUID.randomUUID().toString()+"."+ myFileName;  
                    		String basePath =getClass().getResource("../../../../../../../").getFile().toString();  
                    		basePath=basePath.substring(1);
                            //定义上传路径  
                            String path = basePath+"/img/" + fileName;  
                            File localFile = new File(path);  
                            file.transferTo(localFile);  
                        	
                        }else{
                        	//重命名上传后的文件名  
                        	attachmentName = UUID.randomUUID().toString()+":"+myFileName;  
                    		String basePath =getClass().getResource("../../../../../../../").getFile().toString();  
                    		basePath=basePath.substring(1);
                            //定义上传路径  
                            String path = basePath+"/text/" + attachmentName;  
                            File localFile = new File(path);  
                            file.transferTo(localFile);  
                        }
                   }
                }  
             } 
         }  
		Map<String, Object> map=userService.EditUserImg(code,fileName);
		try {
			PrintWriter out = response.getWriter();
			String json=gson.toJson(map);
			out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value="/userPrivate",method=RequestMethod.POST)
	public void privatechannel(HttpServletRequest request,HttpServletResponse response){
		
		response.setContentType("text/html;charset=utf-8");

		Map<String, Object> map=userService.UserListPrivate();
		
		try {
			PrintWriter out = response.getWriter();
			String json=gson.toJson(map);
			out.println(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}
